package com.cuit.qx.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cuit.qx.config.BasicData;
import com.cuit.qx.controller.CorrectForecastController;
import com.cuit.qx.entity.Config;
import com.cuit.qx.entity.CorrectForecast;
import com.cuit.qx.entity.Product;
import com.cuit.qx.entity.RiskWarning;
import com.cuit.qx.mapper.CorrectForecastMapper;
import com.cuit.qx.service.ConfigService;
import com.cuit.qx.service.CorrectForecastService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuit.qx.service.ProductService;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订正预报表 服务实现类
 * </p>
 *
 * @author lcj
 * @since 2021-11-23
 */
@Service
@Slf4j
public class CorrectForecastServiceImpl extends ServiceImpl<CorrectForecastMapper, CorrectForecast> implements CorrectForecastService {

    @SuppressWarnings("all")
    @Autowired
    private CorrectForecastMapper correctForecastMapper;

    @Resource
    private ConfigService configService;
    @Resource
    private ProductService productService;

    private static final Logger LOG = LoggerFactory.getLogger(CorrectForecastServiceImpl.class);

    @Override
    public void gatherForecast() {

    }

    @Override
    public void removeForecastByDate() {
        try {
            LambdaQueryWrapper<CorrectForecast> wrapper = new LambdaQueryWrapper();
            wrapper.lt(CorrectForecast::getStartDate, getDate(-1));
            int delete = correctForecastMapper.delete(wrapper);
            if (delete > 0) LOG.info("==============删除截止" + getDate(-1) + "前的数据成功===============");
        } catch (Exception e) {
            LOG.error("删除" + getDate(-1) + "月的数据异常：", e);
        }
    }

    /**
     * 获取订正数据
     *
     * @param pattern
     * @param date
     * @param startTime
     * @param moment
     * @return
     */
    @Override
    public List<CorrectForecast> getList(String pattern, String date, String startTime, String moment,String stationName) {
        LambdaQueryWrapper<CorrectForecast> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CorrectForecast::getPattern, pattern);
        wrapper.eq(CorrectForecast::getStartDate, date);
        wrapper.eq(CorrectForecast::getStartTime, startTime);

        switch (moment) {
            case "12":
                wrapper.select(CorrectForecast::getTime12);
                break;
            case "24":
                wrapper.select(CorrectForecast::getTime24);
                break;
            case "36":
                wrapper.select(CorrectForecast::getTime36);
                break;
            case "48":
                wrapper.select(CorrectForecast::getTime48);
                break;
            case "60":
                wrapper.select(CorrectForecast::getTime60);
                break;
            case "72":
                wrapper.select(CorrectForecast::getTime72);
                break;
        }
        if (StrUtil.isNotBlank(stationName)){
            wrapper.like(CorrectForecast::getStaionName,stationName);
        }
        return  this.baseMapper.selectList(wrapper);
    }

    @Override
    public ReturnData makeProduct(String pattern, String date, String startTime, String moment,String stationName, Product product) {
        List<CorrectForecast> list = getList(pattern, date, startTime, moment,stationName);
        if (list.isEmpty()) {
            log.error("查询订正数据为空");
            return new ReturnData(ReturnStateCode.FAILED,"查询订正数据为空,制作产品缺失数据");
        }
        Map<String, Object> data = configService.getData();
        //风险预警产品 入库
        product.setProductType("2");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        product.setCreateTime(format);

        //获取图片
        String url = "http://"+data.get(BasicData.IMAGESIP)+":"+data.get(BasicData.IMAGESPORT)+"/getProductPath?" +
                "mold=dzyb&pattern="+pattern+"&startTime="+startTime+"&date="+date+"&moment="+moment;
        Integer timeOut = Convert.toInt(data.get(BasicData.TIMEOUT)) * 1000;
        String body = HttpRequest.get(url)
                .timeout(timeOut)
                .execute().body();
        if (body.contains("error")){
            return new ReturnData(ReturnStateCode.FAILED,"图片接口数据异常,制作产品缺失数据");
        }
             product.setImagesPath(body);

        return  productService.getProductFile(product);
    }


    public static String getDate(int day) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();

        cal.add(Calendar.MONTH, day);    //得到前一个月

        long date = cal.getTimeInMillis();

        return format.format(new Date(date));
    }
}
